<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="800">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="110px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="姓名" prop="patientName">
            <el-input v-model="formData.patientName" placeholder="患者姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="身份证号" prop="idNumber">
            <el-input
              v-model="formData.idNumber"
              placeholder="请输入身份证号"
              :disabled="formType === 'action.edit'"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select v-model="formData.gender" placeholder="请选择性别" clearable>
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.GENDER)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-show="formType === 'action.add'">
          <el-form-item label="出生日期" prop="birthDate">
            <el-date-picker type="date" v-model="formData.birthDate" :clearable="true" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="所属管理地区" prop="orginDeptId">
            <el-tree-select
              v-model="formData.orginDeptId"
              :data="deptList"
              :props="defaultProps"
              check-strictly
              node-key="id"
              placeholder="请选择区域"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="家庭住址" prop="address">
            <el-input v-model="formData.address" maxlength="100" placeholder="请输入家庭住址" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="联系人" prop="contactPerson">
            <el-input v-model="formData.contactPerson" placeholder="请输入联系人" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系方式" prop="contactPhone">
            <el-input v-model="formData.contactPhone" maxlength="11" placeholder="请输入联系方式" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
const { t } = useI18n() // 国际化
import { FormRules } from 'element-plus'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { defaultProps, handleTree } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import * as townReportApi from '@/api/patient/reportManagement'
import { debounce } from 'lodash'
defineOptions({ name: 'ReportInfoAdd' })

const message = useMessage() // 消息弹窗
const formRef = ref() // 表单 Ref
const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中
const formData = ref({
  patientName: undefined,
  gender: undefined,
  // idNumber: undefined,
  address: undefined,
  // birthDate: undefined,
  contactPerson: undefined,
  contactPhone: undefined,
  orginDeptId: ''
})
const dialogTitle = ref('')
const formRules = reactive<FormRules>({
  patientName: [{ required: true, message: '患者姓名不能为空', trigger: 'blur' }],
  gender: [{ required: true, message: '性别不能为空', trigger: 'blur' }],
  contactPerson: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
  orginDeptId: [{ required: true, message: '所属管理地区不能为空', trigger: 'blur' }],
  idNumber: [
    { required: true, message: '身份证不能为空', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        // 如果是修改模式，跳过校验
        if (formType.value === 'action.edit') {
          callback()
          return
        }
        const idCardRegex =
          /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i
        if (!idCardRegex.test(value)) {
          callback(new Error('请输入有效的身份证号'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  contactPhone: [
    { required: true, message: '联系方式不能为空', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        const phoneRegex = /^1[3-9]\d{9}$/
        if (!phoneRegex.test(value)) {
          callback(new Error('请输入有效的手机号'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})
watch(
  () => formData.value.idNumber,
  (newIdNumber) => {
    if (newIdNumber && newIdNumber.length === 18) {
      const birthDateStr = newIdNumber.substring(6, 14) // 提取身份证号中的出生日期部分
      const year = birthDateStr.substring(0, 4)
      const month = birthDateStr.substring(4, 6)
      const day = birthDateStr.substring(6, 8)
      const birthDate = new Date(`${year}-${month}-${day}`)
      if (!isNaN(birthDate.getTime())) {
        formData.value.birthDate = birthDate // 自动填写出生日期
      }
    }
  }
)
const deptList = ref<Tree[]>([]) // 树形结构
const formType = ref('')
/** 打开弹窗 */
const open = async (type: string, id: string) => {
  dialogVisible.value = true
  dialogTitle.value = t(type)
  resetForm()
  if (id != null) {
    formData.value = await townReportApi.getPatientDetail(id)
    formData.value.gender = parseInt(formData.value.gender)
  }
  formType.value = type
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
/** 上传成功 */
const emit = defineEmits(['success'])
/** 提交表单 */
const submitForm = debounce(async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value
    if (formType.value === 'action.add') {
      await townReportApi.addPatient(data)
      message.success(t('common.createSuccess'))
    } else {
      //身份证号和出生日期不允许修改
      delete data.idNumber
      delete data.birthDate
      await townReportApi.updatePatient(data)
      message.success(t('common.updateSuccess'))
    }
    // 发送操作成功的事件
    emit('success')
    dialogVisible.value = false
  } finally {
    formLoading.value = false
  }
}, 300)
/** 重置表单 */
const resetForm = async (): Promise<void> => {
  // 重置上传状态和文件
  formData.value = {
    patientName: undefined,
    gender: undefined,
    idNumber: undefined,
    address: undefined,
    birthDate: undefined,
    contactPerson: undefined,
    contactPhone: undefined,
    orginDeptId: ''
  }
  formLoading.value = false
  await nextTick()
}
const initDeptTree = async () => {
  // 加载部门树
  deptList.value = handleTree(await DeptApi.getSimpleDeptList())
}
onMounted(() => {
  initDeptTree()
})
</script>
